package com.ksyzt.ksite2.server.dwr;

import java.sql.SQLException;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.IPUSERDAO;
import com.ksyzt.ksite2.server.database.dao.impl.PUSERDAOImpl;
import com.ksyzt.ksite2.shared.modle.PUSERObj;

/**
 *
 * @author 张建设
 *
 */
public class UserUtil {

	private Application getApp() {
		WebContext context = WebContextFactory.get();
		Application app = new Application(context.getHttpServletRequest(),
				context.getHttpServletResponse());
		return app;
	}

	

	/**
	 * 本地用户登录
	 *
	 * @param un
	 * @param pwd
	 * @param code
	 * @return
	 */
	public String[] userlogin(String un, String pwd, String code) {
		String r[] = new String[2];
		r = getApp().userLogin(un, pwd, code);
		return r;
	}

	/**
	 * 验证用户名是否可以注册
	 *
	 * @param name
	 * @return
	 */
	public String[] checkname(String name) {
		String[] r = new String[2];
		if (name == null || name.equals("")) {
			r[0] = "0";
			r[1] = "需要用户名";
		} else if (name.startsWith("QQ") || name.startsWith("新浪用户")) {
			r[0] = "0";
			r[1] = "用户名不能用QQ和新浪用户开头";
		} else {
			IPUSERDAO dao = new PUSERDAOImpl(Application.getConnection());
			try {
				PUSERObj u = dao.findByNAME(name);
				if (u == null) {
					r[0] = "1";
					r[1] = "OK";
				} else {
					r[0] = "0";
					r[1] = "此用户已注册";
				}
			} catch (SQLException e) {
				e.printStackTrace();
				r[0] = "0";
				r[1] = e.getMessage();
			}
		}
		return r;
	}

	/**
	 * 检查电子邮件的合法性
	 *
	 * @param email
	 * @return
	 */
	public String[] check_email(String email) {
		String[] r = new String[2];
		if (email == null || email.equals("")) {
			r[0] = "0";
			r[1] = "需要电子邮件地址";
		} else {
			IPUSERDAO dao = new PUSERDAOImpl(Application.getConnection());
			try {
				PUSERObj u = dao.findByEMAIL(email);
				if (u == null) {
					r[0] = "1";
					r[1] = "OK";
				} else {
					r[0] = "0";
					r[1] = "电子邮件地址已被使用，您可以通过电子邮件找回密码";
				}
			} catch (SQLException e) {
				e.printStackTrace();
				r[0] = "0";
				r[1] = e.getMessage();
			}
		}
		return r;
	}

}
